﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using dbPoll_Application.Helpers;
using NHibernate;
using NHibernate.Linq;


namespace dbPoll_Application.Models
{
    public static class RoleRepository
    {
        public static Boolean Add(Role role)
        {
            ISession session = NHibernateHelper.GetCurrentSession();
            using (ITransaction transaction = session.BeginTransaction())
            {
                session.Save(role);
                transaction.Commit();
                return transaction.WasCommitted;
            }
        }

        public static Boolean Remove(Role role)
        {
            ISession session = NHibernateHelper.GetCurrentSession();
            using (ITransaction transaction = session.BeginTransaction())
            {
                session.Delete(role);
                transaction.Commit();
                if (transaction.WasCommitted)
                {
                    return true;
                }
                return false;
            }
        }

        public static ICollection<Role> GetRoles()
        {
            ISession session = NHibernateHelper.GetCurrentSession();
            var roles = from item in session.Query<Role>()
                        select item;
            return roles.ToList<Role>();
        }

        public static ICollection<Role> GetRolesInheritedByRole(String roleName)
        {
            ISession session = NHibernateHelper.GetCurrentSession();
            var role = (from item in session.Query<Role>()
                         where item.RoleName == roleName
                         select item).FirstOrDefault<Role>();
            return role.InheritedRoles;
        }

        public static Role GetRoleByName(String roleName)
        {
            ISession session = NHibernateHelper.GetCurrentSession();
            var role = (from item in session.Query<Role>()
                        where item.RoleName == roleName
                        select item).FirstOrDefault<Role>();
            return role;
        }

        public static int GetTotalRoleCountByRoleName(String roleName)
        {
            ISession session = NHibernateHelper.GetCurrentSession();
            int roleCount = (from item in session.Query<Role>()
                             where item.RoleName == roleName
                             select item).Count<Role>();
            return roleCount;
        }
    }
}
